package org.jeecg.common.system.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.jeecg.common.exception.AuthException;

import java.util.Date;

/**
 * User：zhongchao
 * Date：2020年08月20日17:19:00
 * Version: v1.0
 * ========================
 */
public class JwtTokenUtil {

    /**
     * 颁发者
     */
    private static final String ISSUER = "xmtkj";

    /**
     * 过期时间
     */
    public static final Long MAX_AGE = 60 * 60 * 24 * 60 * 1000L;

    public static final Algorithm ALGORITHM = Algorithm.HMAC256("xmtkj_8888899999_moeny");

    private static final JWTVerifier JWT_VERIFIER = JWT.require(ALGORITHM).withIssuer(ISSUER).build();


    //加密，传入一个对象和有效期
    public static String sign(String userId, String openId, String sessionKey) {

        return JWT.create().withIssuer(ISSUER)
                .withClaim("userId", userId)
                .withClaim("openId", openId)
                .withClaim("sessionKey", sessionKey)
                .withExpiresAt(new Date(System.currentTimeMillis() + MAX_AGE))
                .sign(ALGORITHM);

    }

    /**
     * 解密 返回openId
     *
     * @param token
     * @return
     */
    public static SignDO unsign(String token) throws AuthException {
        try {
            DecodedJWT decodedJWT = JWT_VERIFIER.verify(token);
            return new SignDO(decodedJWT.getClaim("userId").asString(),
                    decodedJWT.getClaim("openId").asString(),
                    decodedJWT.getClaim("sessionKey").asString());
        } catch (JWTVerificationException e) {
            throw new AuthException("登录验证失败！");
        }
    }

    public static void main(String[] args) {
        String token = JwtTokenUtil.sign("3", "oKaq25B7L2K6v1gdUvNKTPewUZEc", "t+Y4Nziy2wKljOyv/2332A==");
//        SignDO unsign = JwtTokenUtil.unsign("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzZXNzaW9uS2V5IjoiT0RkYUtpaUdaWHE2elN5TUpjTlZkUT09Iiwib3BlbklkIjoib0thcTI1Tk8xMVpEOEVfTlJHZmFzNjAzMXZPNCIsImlzcyI6ImJiayIsImV4cCI6MTU5MjcyMDk5NywidXNlcklkIjoyMn0.Sq_VB4ngRK07XfwJPBMTy9jApHZxx4TJEQCwxv1cA0U");

        System.out.println(token);
    }
}